﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

namespace GroupCheer.FBGraphAPI
{
    public class FBGraphAPIException : Exception
    {
        public string Type { get; private set; }
        public string Message { get; private set; }

        public FBGraphAPIException(string Type, string Message)
        {
            this.Type = Type;
            this.Message = Message;
        }

        internal FBGraphAPIException(HttpWebResponse FBErrorResponse)
        {
            StreamReader sr = new StreamReader(FBErrorResponse.GetResponseStream());
            JObject jsonResponse = JObject.Parse(sr.ReadToEnd());

            FBErrorResponse.Close();
            sr.Close();

            JToken graphAPIErrorType = jsonResponse.SelectToken("error", true).SelectToken("type", false);
            JToken graphAPIErrorMessage = jsonResponse.SelectToken("error", true).SelectToken("message", false);

            this.Type = (graphAPIErrorType as JValue).Value.ToString();
            this.Message = (graphAPIErrorMessage as JValue).Value.ToString();

            jsonResponse = null;
        }
    }
}
